import './App.css';
import {Component} from 'react'

// const list = [{
//     title: 'React',
//     url: 'https://facebook.github.io/react/',
//     author: 'Jordan Walke',
//     num_comments: 3,
//     points: 4,
//     objectID: 0,
// }, {
//     title: 'Redux',
//     url: 'https://github.com/reactjs/redux',
//     author: 'Dan Abramov, Andrew Clark',
//     num_comments: 2,
//     points: 5,
//     objectID: 1,
// }]

const DEFAULT_QUERY = 'redux'
const PATH_SEARCH = '/search'
const PATH_BASE = 'https://hn.algolia.com/api/v1'
const PARAM_SEARCH = 'query='
const PARAM_PAGE = 'page='
const url = `${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${DEFAULT_QUERY}`

// const isSearched = searchTerm => item => item.title.toLowerCase().includes(searchTerm.toLowerCase())

function Search(props) {
    const {value, onChange,children,onSubmit} = props
    // console.log(children)
    return (
        <form action="" onSubmit = {onSubmit}>
            <input className='App-search' type="text" value={value} placeholder='请输入搜索内容' onChange={onChange}/>
            <button type='submit' className='App-searchBt'>{children}</button>
        </form>
    )

}

class Button extends Component{
    render(){
        const {onClick,className = '',children} = this.props
        console.log(onClick)
        return (
            <button onClick={onClick} className={className}>{children}</button>
        )
    }
}

class Table extends Component {
    render() {
        console.log(this.props)
        const {list, onClick, searchTerm} = this.props
        return(
            <div>
                {list.map(item =>
                    <div className='App-datalist' key={item.objectID}>
                        <span>{item.author}</span>
                        <span><a href={item.url}>{item.title}</a></span>
                        <span>{(item.num_comments + item.points) * item.objectID}</span>
                        <Button onClick = {()=>{
                            onClick(item.objectID)
                        }}>删除</Button>
                    </div>
                )}
            </div>
        )

    }
}

class App extends Component {
    constructor(props) {
        super(props)
        this.state = {
            // list,
            searchTerm: DEFAULT_QUERY,
            // 客户端存储
            results:null,
            searchKey:'', // 存储单个 result
            page:0 ,// 当前页数
            nbPages: 50, // 总页数
            // 错误处理
            error:null

        }
        this.onSearchChange = this.onSearchChange.bind(this);
        this.onDismiss = this.onDismiss.bind(this);
        this.onSearchSubmit = this.onSearchSubmit.bind(this)
    };

    setSearchTopStories(result) {
        console.log(result)
        const {hits,page} = result
        const {searchKey,results} = this.state
        const oldHits = results && results[searchKey] ? results[searchKey].hits : []
        const updatedHits = [
            // ...oldHits,
            ...hits
        ]
        console.log(updatedHits)
        this.setState({
            results: {
                ...results,
                [searchKey]: {hits: updatedHits,page}
            }
        })
    }

    // 请求数据
    fetchSearchTopStories(searchTerm){
        const {page} = this.state
        console.log('page=====',page)
        // console.log('88888888',searchTerm)
        // console.log('url======',`${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${searchTerm}&${PARAM_PAGE}${page}`)
        fetch(`${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${searchTerm}&${PARAM_PAGE}${page}`)
            .then(response =>  response.json())
            .then(result => this.setSearchTopStories(result))
            .catch(e => this.setState({error:e}))
    }
    // react 生命周期 render 执行前
    componentDidMount() {
        const {searchTerm} = this.state
        this.setState({searchKey:searchTerm})
        this.fetchSearchTopStories(searchTerm)
    }

    onDismiss(id) {
        console.log(id)
        console.log(this.state)
        const {searchKey,results} = this.state
        const {hits,page} = results[searchKey]
        let updataList = hits.filter(item => item.objectID !== id)
        console.log(updataList)
        this.setState({
            results: {
                ...results,
                [searchKey]:{hits:updataList,page}

            }
        })
    }

    onSearchChange(event) {
        // console.log(event.target.value)
        this.setState({searchTerm: event.target.value})

    }
    // 搜索
    onSearchSubmit(event){
        console.log(this)

        console.log('搜索')
        const {searchTerm,results,} = this.state

        if(!results[searchTerm]){
            this.setState({page:0,searchKey:searchTerm})
            this.fetchSearchTopStories(searchTerm)
        }
        this.setState({searchKey:searchTerm})
        // 阻止默认行为
        event.preventDefault();


    }
    // 下一页
    async onNextpage(){
        console.log('下一页')
        console.log(this)
        const {page, nbPages,searchTerm} = this.state
        if(page > nbPages) return
        await this.setState({page:page + 1})
        this.fetchSearchTopStories(searchTerm)

    }
    //上一页
    async onlastPage(){
        console.log('上一页')
        const {page,searchTerm} = this.state
        if(page<= 0) return
        await this.setState({page:page -1})
        this.fetchSearchTopStories(searchTerm)
    }
    render() {

        const {results, searchTerm,searchKey,error} = this.state
        const page = (results && results[searchKey] && results[searchKey].page) || 0
        const list = (results && results[searchKey] && results[searchKey].hits) || []

        console.log('App-this.props', list)

        if(!list) return null
        console.log(error)
        return (
            <div className="App">
                <header className="App-header">
                    <Search value={searchTerm} onChange={this.onSearchChange} onSubmit = {this.onSearchSubmit}>搜索</Search>
                    { !error ? list ?  <Table list={list} searchTerm={searchTerm} onClick={this.onDismiss}/> : null : <div><p>Something went wrong....</p></div> }
                    <div className='page'>
                        <Button onClick={() => this.onlastPage()}>上一页</Button>
                        <span>{page + 1}</span>
                        <Button onClick={() => this.onNextpage()}>下一页</Button>
                    </div>
                </header>
            </div>
        )
    }
}

export default App;
